﻿using Azure.Core;
using Microsoft.AspNetCore.Mvc;
using XmuAuthen.Models;
using XmuAuthen.Services;
using XmuAuthor.Models;
using XmuAuthor.Services;

namespace UserStores.Models
{
    [ApiController]
    [Route("/api/authorize/{action}")]
    public class AuthorizeApiController: Controller
    {
        private AuthenService authenService;
        private AuthorizationService authorizationService;

        public AuthorizeApiController(AuthenService authenService, AuthorizationService authorizationService)
        {
            this.authenService = authenService;
            this.authorizationService = authorizationService;
        }

        // 新增角色
        [HttpPost]
        public ActionResult addRole()
        {
            // 获取Credential并验证
            string _accessToken_ = Request.Headers[nameof(_accessToken_)].ToString();
            Guid? userId = authenService.GetUserId(_accessToken_);
            if (userId == null)
            {
                return Json(new
                {
                    success = false,
                    msg = "accessToken无效"
                });
            }

            // 查看Credential对应的用户是否具有该Resource
            //if (!checkResource((Guid)userId, "addRole"))
            //{
            //    return Json(new
            //    {
            //        success = false,
            //        msg = "用户无权限"
            //    });
            //}

            // get info:
            string name = Request.Query[nameof(name)].ToString();
            string resources = Request.Query[nameof(resources)].ToString();
            // process resources:
            string[] resourcesArr = resources.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            // add:
            var (success, msg) = authorizationService.AddRole(name, resourcesArr);
            return Ok(new
            {
                success,
                msg
            });
        }

        // 查询角色列表
        public ActionResult getRoles()
        {
            // 获取Credential并验证
            string _accessToken_ = Request.Headers[nameof(_accessToken_)].ToString();
            Guid? userId = authenService.GetUserId(_accessToken_);
            if (userId == null)
            {
                return Json(new
                {
                    success = false,
                    msg = "accessToken无效"
                });
            }

            // 查看Credential对应的用户是否具有该Resource
            if (!authorizationService.checkResource((Guid)userId, "getRoles"))
            {
                return Json(new
                {
                    success = false,
                    msg = "用户无权限"
                });
            }

            // get roles:
            int page = int.Parse(Request.Query[nameof(page)].ToString());
            int pageSize = int.Parse(Request.Query[nameof(pageSize)].ToString());
            var (roles, msg) = authorizationService.GetRoles(page, pageSize);
            return Ok(new
            {
                success = roles != null,
                msg,
                data = roles
            });
        }

        // 删除角色
        [HttpDelete]
        public ActionResult removeRole()
        {
            // 获取Credential并验证
            string _accessToken_ = Request.Headers[nameof(_accessToken_)].ToString();
            Guid? userId = authenService.GetUserId(_accessToken_);
            if (userId == null)
            {
                return Json(new
                {
                    success = false,
                    msg = "accessToken无效"
                });
            }

            // 查看Credential对应的用户是否具有该Resource
            if (!authorizationService.checkResource((Guid)userId, "removeRole"))
            {
                return Json(new
                {
                    success = false,
                    msg = "用户无权限"
                });
            }

            // remove:
            string id = Request.Query[nameof(id)].ToString();
            var (success, msg) = authorizationService.RemoveRole(Guid.Parse(id));
            return Ok(new
            {
                success,
                msg
            });
        }

        // 分配和取消角色
        public ActionResult grant()
        {
            // 获取Credential并验证
            string _accessToken_ = Request.Headers[nameof(_accessToken_)].ToString();

            if (authenService.Check(_accessToken_) == null)
            {
                return Json(new
                {
                    success = false,
                    msg = "accessToken无效"
                });
            }

            string userId = Request.Query[nameof(userId)].ToString();
            // 查看Credential对应的用户是否具有该Resource
            //if(!authorizationService.checkResource(Guid.Parse(userId), "grant"))
            //{
            //    return Json(new
            //    {
            //        success = false,
            //        msg = "用户无权限"
            //    });
            //}

            // get type:
            GrantType grantType = GrantType.NOTSET;  
            string type = Request.Query[nameof(type)].ToString();
            if (type!=null)
                grantType = (type == "GRANT") ? GrantType.GRANT : GrantType.CANCEL;

            string roleIds = Request.Query[nameof(roleIds)].ToString();
            // process roleIds:
            string[] roleIdsArr = roleIds.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            List<Guid> roleIdList = new List<Guid>();
            foreach (var roleId in roleIdsArr)
                roleIdList.Add(Guid.Parse(roleId));
            // grant:
            var (success, msg) = authorizationService.Grant(Guid.Parse(userId), roleIdList, grantType);
            return Ok(new
            {
                success,
                msg
            });
        }

        public ActionResult addResource([FromBody] Resource resource)
        {
            // 获取Credential并验证
            string _accessToken_ = Request.Headers[nameof(_accessToken_)].ToString();
            Guid? userId = authenService.GetUserId(_accessToken_);
            if (userId == null)
            {
                return Json(new
                {
                    success = false,
                    msg = "accessToken无效"
                });
            }

            // 查看Credential对应的用户是否具有该Resource
            if (!authorizationService.checkResource((Guid)userId, "addUser"))
            {
                return Json(new
                {
                    success = false,
                    msg = "用户无权限"
                });
            }

            var (success,msg) = authorizationService.AddResource(resource);
            return Ok(new
            {
                success,
                msg
            });


        }

        
    }
}
